package com.qijian.maindata.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qijian.common.utils.uuid.IdUtils;
import com.qijian.maindata.domain.Line;
import com.qijian.maindata.domain.LineBom;
import com.qijian.maindata.domain.Project;
import com.qijian.maindata.domain.query.LineBomQuery;
import com.qijian.maindata.domain.query.LineQuery;
import com.qijian.maindata.domain.vo.LineVo;
import com.qijian.maindata.mapper.LineMapper;
import com.qijian.maindata.service.ILineService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 工艺线路Service业务层处理
 *
 * @author qijian
 * @date 2021-09-03
 */
@Service
@RequiredArgsConstructor
public class LineServiceImpl extends ServiceImpl<LineMapper, Line> implements ILineService {

    private final LineMapper lineMapper;

    @Override
    public Page<LineVo> pageVo(Page<Project> page, Wrapper<LineQuery> queryWrapper) {
        return lineMapper.selectPageVo(page, queryWrapper);
    }

    @Override
    public List<LineVo> listVo(Wrapper<LineQuery> queryWrapper) {
        return lineMapper.selectPageVo(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(Line line) {
        line.setLineCode(IdUtils.getNumber("GYXL-", lineMapper.countCurrentDateWithDel() + 1));
        int result = lineMapper.insert(line);
        if (CollectionUtil.isNotEmpty(line.getLineBomList())) {
            line.getLineBomList().forEach(item -> item.setLineId(line.getLineId()));
            lineMapper.saveDetail(line.getLineBomList());
        }
        return result > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDetail(List<LineBom> list) {
        lineMapper.saveDetail(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(Line line) {
        int result = lineMapper.updateById(line);
        line.getLineBomList().forEach(item -> item.setLineId(line.getLineId()));
        lineMapper.delDetail(line.getLineId());
        lineMapper.saveDetail(line.getLineBomList());
        return result > 0;
    }

    @Override
    public int bomCount(Wrapper<LineBomQuery> queryWrapper) {
        return lineMapper.bomCount(queryWrapper);
    }
}
